package com.kefu.chat.listener;

import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.kefu.chat.mapper.ChatSessionMapper;
import com.kefu.chat.model.ChatSession;
import com.kefu.chat.model.ChatUser;
import com.kefu.chat.service.ChatCacheService;
import com.kefu.common.util.JacksonUtil;
import com.kefu.crm.event.CrmCustomerEvent;
import com.kefu.crm.model.CrmCustomer;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.event.EventListener;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.List;
import java.util.Objects;

@Slf4j
@Component
public class ChatListener {
    @Autowired
    private ChatCacheService chatCacheService;
    @Resource
    private ChatSessionMapper chatSessionMapper;
    @EventListener(CrmCustomerEvent.class)
    public void crmCustomerBlackEvent(CrmCustomerEvent event) {
        CrmCustomer crmCustomer = event.getCrmCustomer();
        String name = crmCustomer.getName();
        Integer status = crmCustomer.getCustomerStatus();
        List<ChatSession> chatSessions = chatSessionMapper.selectList(Wrappers.lambdaQuery(ChatSession.class)
                .eq(ChatSession::getCustomerId, crmCustomer.getCustomerId()));
        log.info("需要变更的会话信息 : {}", JacksonUtil.toString(chatSessions));
        chatSessions.forEach(
                chatSession -> {
                    chatSession.setUserName(name);
                    chatSession.setBlackMode(3 != status ? 0 : 1);
                    chatSessionMapper.updateById(chatSession);
                    String userId = chatSession.getUserId();
                    ChatUser user = chatCacheService.getUser(userId);
                    if (Objects.nonNull(user)) {
                        user.setUserName(name);
                        user.setBlackMode(3 != status ? 0 : 1);
                        chatCacheService.setUser(user);
                        log.info("需要变更的访客信息 : {}", JacksonUtil.toString(user));
                    }
                }
        );
    }
}
